package com.farm.template.utils;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.farm.parameter.FarmParameterService;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;

public class FreeMarkerUtils {
	
	/**执行模板引擎并返回结果
	 * @param templateStr
	 * @param attrs
	 * @param filename 模板信息，用于报错时展示模板信息
	 * @return
	 */
	public static String getTemplateString(String templateStr, Map<String, Object> attrs, String filename) {
		Writer out = new StringWriter();
		try {
			String uuid = UUID.randomUUID().toString();
			StringTemplateLoader stringLoader = new StringTemplateLoader();
			stringLoader.putTemplate(uuid, templateStr);
			Configuration templateCfg = new Configuration();
			templateCfg.setTemplateLoader(stringLoader);
			freemarker.template.Template templateRunner;
			templateRunner = templateCfg.getTemplate(uuid, "utf-8");
			templateRunner.process(attrs, out);
			String output = out.toString();
			return output;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e + ",模板文件：" + filename);
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 刪除目錄和子目錄和文件
	 * 
	 * @param directory
	 */
	public static void deleteDirectory(File directory) {
		if (directory.exists()) {
			File[] files = directory.listFiles();
			if (files != null) {
				for (File file : files) {
					if (file.isDirectory()) {
						deleteDirectory(file); // 递归删除子目录
					} else {
						file.delete(); // 删除文件
					}
				}
			}
			directory.delete(); // 删除当前目录
		}
	}

	public static void main(String[] args) {
		Map<String, Object> attrs = new HashMap<String, Object>();
		Map<String, Object> attrs1 = new HashMap<String, Object>();
		attrs1.put("name", "xxx");
		attrs.put("project", attrs1);
		System.out.println(getTemplateString("${project.name} ", attrs, "测试"));
	}

	/**
	 * 獲得項目实例模板根目录
	 * 
	 * @param activeId
	 * @return
	 */
	public static String getActiveTemplatePath(String activeId, String templateCode) {
		String dirPath = getActivePath(activeId) + File.separator + templateCode;
		return dirPath;
	}
	/**
	 * 獲得項目实例根目录
	 * 
	 * @param activeId
	 * @return
	 */
	public static String getActivePath(String activeId) {
		String tempFile = FarmParameterService.getInstance().getParameter("config.doc.file.export");
		String dirPath = tempFile + File.separator + activeId;
		return dirPath;
	}

//private static Configuration templateCfg = new Configuration();
//
//	
//
//	@Override
//	@Transactional
//	public void runTemplate(String projectid, String workpath) {
//		try {
//			Codeproject project = farmCodeProjectManagerImpl.getFarmCodeProjectEntity(projectid);
//			Codeguide guide = (Codeguide) BeanUtils.cloneBean(getFarmCodeGuideEntity(project.getGuideid()));
//			StringTemplateLoader stringLoader = new StringTemplateLoader();
//			Map<String, Object> map = getTemplateParas(projectid);
//			// 随机数
//			if (guide.getApprandom().equals("1")) {
//				guide.setAppcode(guide.getAppcode() + String.valueOf(new Date().getTime()).substring(8));
//			}
//			// 包
//			List<DBRule> listPackageRule = new ArrayList<DBRule>();
//			listPackageRule.add(new DBRule("PROID", projectid, "="));
//			List<Codepackage> packs = farmCodePackageDao.selectEntitys(listPackageRule);
//			for (Codepackage pack : packs) {
//				// 文件
//				{
//					List<DBRule> listTemplateRule = new ArrayList<DBRule>();
//					listTemplateRule.add(new DBRule("PACKID", pack.getId(), "="));
//					List<Codetemplet> templates = farmCodeTempletDao.selectEntitys(listTemplateRule);
//					for (Codetemplet codetemplate : templates) {
//						FileOutputStream fops = null;
//						Writer out = null;
//
//						stringLoader.putTemplate(codetemplate.getId(), codetemplate.getTemcontent());
//						templateCfg.setTemplateLoader(stringLoader);
//						Template template;
//						template = templateCfg.getTemplate(codetemplate.getId(), "utf-8");
//						String path = (workpath + File.separator
//								+ parseCodeMark(guide, pack.getPackcode()).replace(".", "/") + File.separator
//								+ parseCodeMark(guide, codetemplate.getFilename())).replace("/", "\\").replace("\\",
//										File.separator);
//						File outPutFile = new File(path);
//						outPutFile.getParentFile().mkdirs();
//						try {
//							fops = new FileOutputStream(outPutFile);
//							out = new OutputStreamWriter(fops, "utf-8");
//							template.process(map, out);
//						} finally {
//							fops.close();
//							out.close();
//						}
//					}
//				}
//			}
//			project.setDirpath(workpath);
//			LoginUser user = new LoginUser() {
//				@Override
//				public String getName() {
//					return "none";
//				}
//
//				@Override
//				public String getLoginname() {
//					return "none";
//				}
//
//				@Override
//				public String getId() {
//					return "none";
//				}
//			};
//			farmCodeProjectManagerImpl.editFarmCodeProjectEntity(project, user);
//		} catch (Exception e) {
//			throw new RuntimeException(e);
//		}
//	}
}
